
/**
 * PromptSidebar - 提示词管理工具
 * Copyright (C) 2025
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 */

export default defineBackground(() => {
  // 监听快捷键命令
  browser.commands.onCommand.addListener(async (command) => {
    if (command === 'toggle-sidebar') {
      try {
        // 获取当前活动标签页
        const [tab] = await browser.tabs.query({ active: true, currentWindow: true });
        if (tab?.id) {
          // 打开或关闭 sidepanel
          await browser.sidePanel.open({ tabId: tab.id });
        }
      } catch (error) {
        console.error('打开侧边栏失败:', error);
      }
    }
  });

  // 监听扩展图标点击事件（仅在 action API 可用时）
  if (browser.action && browser.action.onClicked) {
    browser.action.onClicked.addListener(async (tab) => {
      try {
        if (tab.id) {
          // 打开 sidepanel
          await browser.sidePanel.open({ tabId: tab.id });
        }
      } catch (error) {
        console.error('打开侧边栏失败:', error);
      }
    });
  }

  // 监听来自 content script 和 sidepanel 的消息
  browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
    if (message.type === 'INSERT_TEXT') {
      // 转发消息到 content script
      browser.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]?.id) {
          browser.tabs.sendMessage(tabs[0].id, message);
        }
      });
    } else if (message.type === 'SHOW_VARIABLE_MODAL') {
      // 转发变量输入请求到 sidepanel
      browser.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]?.id) {
          // 打开 sidepanel 并发送消息
          browser.sidePanel.open({ tabId: tabs[0].id }).then(() => {
            // 延迟发送消息，确保 sidepanel 已加载
            setTimeout(() => {
              browser.runtime.sendMessage({
                type: 'SHOW_VARIABLE_MODAL',
                data: message.data
              });
            }, 100);
          });
        }
      });
    } else if (message.type === 'REPLACE_TEXT') {
      // 转发文本替换消息到 content script
      browser.tabs.query({ active: true, currentWindow: true }, (tabs) => {
        if (tabs[0]?.id) {
          browser.tabs.sendMessage(tabs[0].id, message);
        }
      });
    }
    return true;
  });

  console.log('提示词管理工具背景脚本已启动 - Sidepanel 模式');
});
